<template>
  <view class="uni-container">
    <view class="form-header">
      <text class="form-title">编辑申请信息</text>
    </view>
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <view class="form-section">
        <view class="section-title">基本信息</view>
        <uni-forms-item name="company" label="所属公司" required>
          <uni-easyinput placeholder="请输入所属公司名称" v-model="formData.company" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="contact" label="联系人" required>
          <uni-easyinput placeholder="请输入联系人姓名" v-model="formData.contact" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="phone" label="联系方式" required>
          <uni-easyinput placeholder="请输入联系电话" v-model="formData.phone" trim="both"></uni-easyinput>
        </uni-forms-item>
      </view>
      
      <view class="form-section">
        <view class="section-title">测试信息</view>
        <uni-forms-item name="exchange" label="待测试交易所" required>
          <uni-data-checkbox v-model="formData.exchange" :localdata="formOptions.exchange_localdata"></uni-data-checkbox>
        </uni-forms-item>
        <uni-forms-item name="accountCount" label="测试账号数量" required>
          <picker @change="pickerChange($event, 'accountCount')" :range="formOptions.accountCount_data" :value="formOptions.accountCount_index">
            <view class="picker-view">{{formOptions.accountCount_data[formOptions.accountCount_index] || "请选择测试账号数量..."}}</view>
          </picker>
        </uni-forms-item>
      </view>
      
      <view class="form-section">
        <view class="section-title">期货公司信息</view>
        <uni-forms-item name="futuresCompany" label="所属期货公司" required>
          <uni-easyinput placeholder="请输入期货公司名称" v-model="formData.futuresCompany" trim="both"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="futuresContact" label="期货公司对接人" required>
          <uni-easyinput placeholder="请输入期货公司对接人姓名" v-model="formData.futuresContact" trim="both"></uni-easyinput>
        </uni-forms-item>
      </view>
      
      <view class="form-section">
        <view class="section-title">状态信息</view>
        <uni-forms-item name="status" label="申请状态">
          <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
        </uni-forms-item>
        <uni-forms-item name="createTime" label="创建时间">
          <uni-datetime-picker return-type="timestamp" v-model="formData.createTime"></uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item name="updateTime" label="更新时间">
          <uni-datetime-picker return-type="timestamp" v-model="formData.updateTime"></uni-datetime-picker>
        </uni-forms-item>
      </view>
      
      <view class="form-section">
        <view class="section-title">系统信息</view>
        <uni-forms-item name="ip" label="提交IP地址">
          <uni-easyinput placeholder="提交IP地址" v-model="formData.ip" disabled></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="userAgent" label="用户代理">
          <uni-easyinput placeholder="用户代理" v-model="formData.userAgent" disabled></uni-easyinput>
        </uni-forms-item>
      </view>
      
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 120px;" @click="submit">保存修改</button>
        <button class="uni-button" style="width: 120px; margin-left: 15px;" @click="goBack">返回列表</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/acc.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'acc';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "company": "",
        "contact": "",
        "phone": "",
        "exchange": "",
        "accountCount": 1,
        "futuresCompany": "",
        "futuresContact": "",
        "status": "pending",
        "createTime": null,
        "updateTime": null,
        "ip": "",
        "userAgent": ""
      }
      return {
        formData,
        formOptions: {
          "exchange_localdata": [
            {
              "value": "上期/能源所",
              "text": "上期/能源所"
            },
            {
              "value": "中金所",
              "text": "中金所"
            },
            {
              "value": "大商所",
              "text": "大商所"
            },
            {
              "value": "郑商所",
              "text": "郑商所"
            },
            {
              "value": "广期所",
              "text": "广期所"
            }
          ],
          "accountCount_data": numberRange(1, 100),
          "accountCount_index": null,
          "status_localdata": [
            {
              "value": "pending",
              "text": "待审核"
            },
            {
              "value": "approved",
              "text": "已通过"
            },
            {
              "value": "rejected",
              "text": "已拒绝"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("company,contact,phone,exchange,accountCount,futuresCompany,futuresContact,status,createTime,updateTime,ip,userAgent").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            for (let key in this.formOptions) {
              let pickerIndex = key.lastIndexOf("_index")
              if (pickerIndex > -1) {
                let fieldName = key.substring(0, pickerIndex)
                let fieldData = this.formOptions[fieldName + "_data"];
                if (data[fieldName] && fieldData && fieldData.indexOf(data[fieldName]) > -1) {
                  this.formOptions[fieldName + "_index"] = fieldData.indexOf(data[fieldName])
                }
              }
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      goBack() {
        uni.navigateBack()
      }
    }
  }
</script>

<style>
.form-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.form-title {
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.form-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #495057;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #dee2e6;
}

.picker-view {
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #333;
}

.uni-button-group {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.uni-button {
  border-radius: 6px;
  font-weight: 500;
}

.uni-forms-item {
  margin-bottom: 15px;
}

.uni-forms-item__label {
  font-weight: 500;
  color: #495057;
}
</style>
